package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.db.datasource.JdbcTemplateUtil;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.system.model.SysDataSource;
import com.ccp.dev.system.model.SysObjRights;
import com.ccp.dev.system.model.SysPopupRemind;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysDataSourceService;
import com.ccp.dev.system.service.SysObjRightsService;
import com.ccp.dev.system.service.SysPopupRemindService;
import com.ccp.dev.system.service.SysUserService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * sys_popup_remind 信息操作处理控制器
 *
 * @author hw
 * @date 2019-09-17 15:54:13
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_SYSTEM + "/sysPopupRemind")
public class SysPopupRemindController extends SysBaseController {
    @Resource
    private SysPopupRemindService sysPopupRemindService;
    @Resource
    private SysDataSourceService sysDataSourceService;
    @Resource
    private SysObjRightsService sysObjRightsService;


    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到sys_popup_remind首页")
    public String list() {
        return "sysPopupRemind/list";
    }

    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到sys_popup_remind新增页面")
    public String add(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        return "sysPopupRemind/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: sysPopupRemind 保存的对象
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存sys_popup_remind数据")
    public Object save(@RequestBody SysPopupRemind sysPopupRemind) {
        String id = sysPopupRemind.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            //新增操作
            //新增数据前生成随机Id
            sysPopupRemind.setId(UUIDUtils.getUUIDFor32());
            sysPopupRemind.setCreatetime(new Date());
            result = sysPopupRemindService.add(sysPopupRemind);
        } else {
            //修改操作
            result = sysPopupRemindService.update(sysPopupRemind);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除sys_popup_remind数据")
    public Object delete(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            return fail("delete.failure.message");
        }
        int result = sysPopupRemindService.delByIdArray(id.split(","));
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 启动所选数据
     * @param id
     * @return
     */
    @PostMapping("/startRemind")
    @ResponseBody
    @Action(description="根据主键ID启动sys_popup_remind数据")
    public Object startRemind(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            return fail("delete.failure.message");
        }
        int result = sysPopupRemindService.startRemind(id.split(","));
        return result > 0 ? getResultDataSuccess("operation.success") : getResultDataError("operation.failure");
    }

    /**
     * 停止所选数据
     * @param id
     * @return
     */
    @PostMapping("/stopRemind")
    @ResponseBody
    @Action(description="根据主键ID停止sys_popup_remind数据")
    public Object stopRemind(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            return fail("delete.failure.message");
        }
        int result = sysPopupRemindService.stopRemind(id.split(","));
        return result > 0 ? getResultDataSuccess("operation.success") : getResultDataError("operation.failure");
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询sys_popup_remind的一条数据")
    public Object get(@RequestParam("id") String id) {
        SysPopupRemind sysPopupRemind = sysPopupRemindService.getOneById(id);
        if (null == sysPopupRemind) {
            return getResultDataError("get.failure");
        }
        return getResultDataSuccess("get.success",sysPopupRemind);
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询sys_popup_remind")
    public Object list(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        //分页数据
        List<SysPopupRemind> pageDatas = sysPopupRemindService.queryList(queryFilter);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }

    /**
     * 查询所有的数据源信息
     * @param request
     * @return
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping("/queryDataSourceList")
    @ResponseBody
    @Action(description = "查询所有的数据源信息")
    public Object queryDataSourceList(HttpServletRequest request){
        QueryFilter queryFilter = new QueryFilter(request,false);
        List<SysDataSource> sysDataSourceList = sysDataSourceService.queryList(queryFilter);
        return getResultDataSuccess("operation.success",sysDataSourceList);
    }

    /**
     * 验证SQL
     * @param sql 前台页面中的SQL语句
     * @param dsAlias 前台页面中的数据源别名
     * @return
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping("/validSql")
    @ResponseBody
    @Action(description = "验证SQL")
    public Object validSql(@RequestParam("sql") String sql,@RequestParam("dsAlias")String dsAlias){
        SysDataSource sysDataSource = sysDataSourceService.getByAlias(dsAlias);
        Boolean result = sysDataSourceService.validSql(sql,sysDataSource);
        if(result){
            return getResultDataSuccess("operation.success");
        }else{
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 跳转到授权页面
     * @param request
     * @param modelMap
     * @return
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/authorization")
    @Action(description="跳转到授权页面")
    public String authorization(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        String objType = RequestUtil.getString(request,"objType");
        modelMap.put("objType",objType);
        return "sysPopupRemind/authorization";
    }

    /**
     * 保存提醒功能权限
     * @param sysObjRights 接收页面传递过来的参数
     * @return
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @PostMapping(value="/saveRights",consumes = "application/json; charset=utf-8")
    @Action(description = "保存提醒功能权限")
    @ResponseBody
    public Object saveRights(@RequestBody List<SysObjRights> sysObjRights){
        int result = sysObjRightsService.save(sysObjRights);
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
     * 获取权限信息
     * @param id
     * @return
     * @auther: hw
     * @date: 2019-09-17 15:54:13
     */
    @RequestMapping("/getPopupRemindRights")
    @ResponseBody
    @Action(description = "获取权限信息")
    public Object getPopupRemindRights(@RequestParam("id") String id) {
        List<SysObjRights> objRights = sysPopupRemindService.getPopupRemindRights(id);
        return getResultDataSuccess("get.success",objRights);
    }

    @RequestMapping("/showSize")
    @Action(description = "获取userId的弹框数据的大小，用来判断是否需要弹框")
    @ResponseBody
    public Object showSize(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = RequestUtil.getString(request, "userId", "");
        SysUser user = (SysUser) ContextUtil.getCurrentUser();
        if (StringUtil.isNotEmpty(userId)) {
            user = AppUtil.getBean(SysUserService.class).getById(userId);
        }
        // 获取用户能生效的列表
        List<SysPopupRemind> reminds = null;
        try {
            reminds = sysPopupRemindService.getByUser(user);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        int size = 0;
        for (SysPopupRemind spr : reminds) {
            String sql = spr.getSql().replace("{curUserId}", ContextUtil.getCurrentUserId().toString());
            int count = JdbcTemplateUtil.getNewJdbcTemplate(spr.getDsalias()).queryForObject(sql, Integer.class);
            if (count <= 0) {// 没有数据
                continue;
            }
            size++;
        }
        return getResultDataSuccess("get.success",size);
    }

    @RequestMapping("/show")
    @Action(description = "展示某个用户的弹框，默认当前用户")
    @ResponseBody
    public ResultData show(HttpServletRequest request) throws Exception {
        String userId = RequestUtil.getString(request, "userId", "");
        SysUser user = (SysUser) ContextUtil.getCurrentUser();
        if (StringUtil.isNotEmpty(userId)) {
            user = AppUtil.getBean(SysUserService.class).getById(userId);
        }
        // 获取用户能生效的列表
        List<SysPopupRemind> reminds = sysPopupRemindService.getByUser(user);
        List<Map<String,Object>> jsonList = new ArrayList<Map<String,Object>>();
        for (SysPopupRemind spr : reminds) {
            String sql = spr.getSql().replace("{curUserId}", ContextUtil.getCurrentUserId().toString());
            int count = JdbcTemplateUtil.getNewJdbcTemplate(spr.getDsalias()).queryForObject(sql,Integer.class);
            if (count <= 0) {// 没有数据
                continue;
            }
            Map<String,Object> map = new HashMap<>();

            String str = "您有 " + count + " 个 " + spr.getDesc();
            map.put("msg", str);
            map.put("url", spr.getUrl());
            map.put("subject", spr.getSubject());
            jsonList.add(map);
        }
        return getResultDataSuccess("operation.success",jsonList);
    }

}
